package com.learn.base;

import cn.hutool.core.util.HexUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

/**
 * 密码工具类
 *
 * @author zhouhaofeng
 * @version 2022/10/21 0021
 * @see [相关类/方法]
 * @since [cloud-phone-baseline]
 */
@Slf4j
public class PasswordUtil
{
	private PasswordUtil ()
	{

	}

	/**
	 * 验证密码是否一致
	 *
	 * @param password     明文密码
	 * @param encryptedPwd 加密后的密码
	 * @return true 密码一致 false 密码不一致
	 */
	public static boolean verifyPassword (String password, String encryptedPwd)
	{
		// 没有密码场景
		if (encryptedPwd == null)
		{
			return false;
		}
		String[] splitArray = encryptedPwd.split ("\\$");
		if (splitArray.length != 2)
		{
			return false;
		}
		return splitArray[1].equals (PBKDF2Util.encrypt (password, splitArray[0].getBytes (StandardCharsets.UTF_8)));
	}

	/**
	 * PBKDF2加密密码（salt$password）
	 *
	 * @param password 明文密码
	 * @return 加密后的密码
	 */
	public static String encryptPassword (String password)
	{
		try
		{
			String salt = HexUtil.encodeHexStr (PBKDF2Util.generateSalt ());
			String encryptResult = PBKDF2Util.encrypt (password, salt.getBytes (StandardCharsets.UTF_8));
			return String.format ("%s$%s", salt, encryptResult);
		}
		catch (NoSuchAlgorithmException e)
		{
			log.error ("encryptPassword exception : ", e);
		}
		return null;
	}
}
